$(function () {
    //手机端不连接
    connection();
});
var ws,
    port = window['port'] ? port : '2012',
    wsUrl = 'ws://127.0.0.1:' + port;
function connection() {
    if (is_remote_print) {
        //远程打印
        wsUrl = 'ws://' + remote_ip + ':2012';
    }
    console.log(wsUrl);

    if ('WebSocket' in window) {
        try{
            ws = new WebSocket(wsUrl);
        }catch (e) {
            console.log(e)
            console.log(ws)
        }
    } else if ('MozWebSocket' in window) {
        ws = new MozWebSocket(wsUrl);
    } else {
        alert('当前浏览器不支持');
    }


    //注册各类回调
    ws.onopen = function () {
        console.log('连接打印后台成功');
        //alert('连接打印后台成功');
    }

    ws.onclose = function () {
        // alert('与打印后台断开连接');
        console.log('与打印后台断开连接');
    }
    ws.onerror = function () {
        // alert('数据传输发生错误');
        layer.msg('打印服务未开启', { time: 4000 });
    }
    ws.onmessage = function (receiveMsg) {
        if (receiveMsg.data.split("|")[0] == "B_GetPrinterStatus") {
            var ret = receiveMsg.data.split("|")[1];
            if (ret == 2) {
                document.getElementById("status").value = "2:USB端口开启失败";
                console.log(333);
                return;
            }
            else if (ret == 7) {
                document.getElementById("status").value = "7:纸张/碳带用完！";
                console.log(444);
                return;
            }
            else if (ret == 4) {
                document.getElementById("status").value = "4:内存溢出！";          //4:内存溢出！
                console.log(555);
                return;
            }
            else if (ret == 4) {
                document.getElementById("status").value = "4 碳带用完或安装错误！";                       //碳带用完或安装错误！";
                console.log(666);
                return;
            }
            else if (ret == 3) {
                document.getElementById("status").value = "3:条码格式错误！";           //3:条码格式错误！";
                console.log(777);
                return;
            }
            else if (ret == 1) {
                document.getElementById("status").value = "1:打印命令错误！";                 //1:打印命令错误！
                console.log(888);
                return;
            }
            else if (ret == 6) {
                document.getElementById("status").value = "6:串口通信异常！";                 //6:串口通信异常！
                console.log(999);
                return;
            }
            else if (ret == 50) {
                document.getElementById("status").value = "50:打印机忙碌！";                 //50:打印机忙碌！
                console.log(10);
                return;
            }
            else if (ret == 12) {
                document.getElementById("status").value = "12:打印机暂停！";                 //12:打印机暂停
                console.log(11);
                return;
            }
            else if (ret == 9) {
                document.getElementById("status").value = "9:未取得返回值";                 //9:未取得返回值
                console.log(12);
                return;
            }
            else if (ret == 0) {
                document.getElementById("status").value = "0:等待列印!";                 //0:等待列印!
                console.log(13);
                return;
            }

        }
    }
}

function getStatus() {
    ws.send('B_EnumUSB');
    ws.send('B_CreateUSBPort|1');
    ws.send('B_GetPrinterStatus');
    ws.send('B_ClosePrn');
}

function print_barcode(obj) {
    var tr = $(obj).closest("tr");
    var data = [{
        client_name: client_name,
        tool_name: tr.find("td.tool_name").text(),
        class_name: tr.find("td.class_name").text(),
        bar_code: tr.find("td.bar_code").text(),
        class: tr.find("td.class").text(),
        voltage: tr.find("td.voltage").text(),
        guige_xinghao: tr.find("td.guige_xinghao").text(),
    }];
    printCode(data);
}

//打印IP
function print_ip(obj,className) {
    var tr = $(obj).closest("tr");
    var data = [{
        name: tr.find("td.name").text(),
        ip: tr.find("td."+className).text(),
    }];
    //尝试向打印后台发送消息
    ws.send('B_EnumUSB');
    ws.send('B_CreateUSBPort|1');
    ws.send('B_Set_Darkness|12');//设定打印头打印热度，范围：0～15，默认是 8。
    ws.send('B_Set_Direction|B');       //设置打印方向，默认为反向， B为正向
    ws.send('B_Set_Backfeed|F');        //功能选项，"B" 关闭 Back feed。"F" 启动 Back feed。 它可吐出一定长度，让使用者看到印出结果。
    ws.send('B_Set_Labwidth|430');//设置标签宽度
    ws.send('B_Set_Labgap|240|24');//int B_Set_Labgap(int lablength, int gaplength)设定标籤长度及 GAP 长度
    for (var i in data) {
        var item = data[i];
        if (item.ip == '' || item.ip == '/') {
            layer.msg('ip空，不能打印');
            break;
        }
        //ws.send('B_Set_Originpoint|0|0');//设置打印初始位置
        ws.send('B_Draw_Box|22|10|4|410|232');//画方框，起始点x坐标，起始点y坐标，线宽，对角点x坐标，对角点y坐标
        ws.send('B_Prn_Text_TrueType|38|18|28|宋体|1|600|0|0|0|C1|设备：' + item.name);//打印文本，x坐标，y坐标，尺寸，字体，文字旋转 1 -> 0度 2 -> 90度 3 -> 180度 4 -> 270度，字体粗细，斜体，底线，删除线，id,文本内容
        ws.send('B_Prn_Text_TrueType|38|55|28|宋体|1|600|0|0|0|C2|编号：' + item.ip);
        ws.send('B_Print_Out|1');
        sleep(1000);
    }
    ws.send('B_ClosePrn');
}


/* 批量打印条形码 */
function batch_print() {
    // console.log(ws.readyState)
    if (ws.readyState != 1){
        layer.msg('打印服务未开启', { time: 4000 });
        return false;
    }
    var doms = $("tbody tr > td:first-child input:checkbox:checked");
    var l = doms.length;
    if (l == 0) {
        alert('请先选择一个');
        return;
    }

    var data = [];
    var i = 0;
    doms.each(function () {
        data[i++] = {
            client_name: client_name,
            tool_name: $(this).closest("tr").find("td.tool_name").text(),
            class_name: $(this).closest("tr").find("td.class_name").text(),
            bar_code: $(this).val(),
            class: $(this).closest("tr").find("td.class").text(),
            voltage: $(this).closest("tr").find("td.voltage").text(),
            guige_xinghao: $(this).closest("tr").find("td.guige_xinghao").text(),
        };
    });
    printCode(data);
}
/* 按概要信息打印条形码 */
function printByGaiyao(client_name, batchNum, index, count, obj) {
    var data = [];
    var chars_count;//样品号位数 3 or 4
    var bar_codes = $(obj).closest("tr").find("td.bar_codes").text();
    var tool_name = $(obj).closest("tr").find("td.tool_name").text();
    var tr = $(obj).closest("tr");
    for (var i = 0; i < count; i++) {
        if (bar_codes.length == 21 || index > 999) {
            //样品号是 4位
            chars_count = 4;
        } else {
            //样品号是 3位
            chars_count = 3;
        }
        // var sub3 = ('000' + (index++)).slice(-3);
        var sub3 = ('0000' + index).slice((-1) * chars_count);
        data[i] = {
            bar_code: batchNum + sub3,
            client_name: client_name,
            tool_name: tool_name,
            voltage: tr.find("td.voltage").text(),
        };
        index++;
    }
    printCode(data);
}

function sleep(time) {
    var timeStamp = new Date().getTime();
    var endTime = timeStamp + time;
    while (true) {
        if (new Date().getTime() > endTime) {
            return;
        }
    }
}
